var express = require('express');
var router = express.Router();
var dbconnect=require('../models/dbconnect.js')
/* GET users listing. */
router.get('/', function(req, res, next) {
  res.send('respond with a resource');
});
//登录页
router.get('/login',function(req,res){
  res.render('loginad',{

  })
})
//登录接口
router.post('/logad',function(req,res){
    var admintorObj={
      username:req.body.username,
      password:req.body.password
    }
  dbconnect('Administrators').then(function({coll,dbCon}){
      coll.find(admintorObj).toArray(function(error,data){
        if (error) throw error;
        console.log(data.length)
        if(data.length == 0){
          res.json({
            code:0,
            msg:'登录失败'

          })
        }else{
          // console.log(data[0].username)
          
          req.session.username=data[0].username
          console.log(req.session)
          res.json({
            code:1,
            msg:'登录成功'
          })
          dbCon.close();
          
        }

      })
  })
    
})


//注册页
router.get('/register',function(req,res){
  res.render('registerad',{
    
  })
})

//注册接口
router.post('/regad',function(req,res){
  console.log(req.body)
  dbconnect('Administrators').then(function({coll,dbCon}){
      //先查询数据库管理员是否存在
      var admintor={
        username:req.body.username,
        password:req.body.password,
        regtime:new Date()

      }
      coll.find({username:req.body.username}).toArray(function(error,data){
          if(error) throw error;
          console.log(data.length)
          if(data.length>0){
            res.json({
              code:0,
              msg:'用户名已被注册'
            })
            dbCon.close();
          }else{
            //向数据库插入数据
            coll.insertOne(admintor,function(error,data){
                console.log(data);
                
                res.json({
                  code:1,
                  msg:'注册成功'
                })
                dbCon.close();
                
            })
          }
      })
  })
 
})
module.exports = router;
